package com.snda.dw.lidejia.ftpfilesender;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Hello world!
 *
 */
public class FileSender {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileSender.class);

    public static void main(String[] args) {
        final String serverHost = args[0];
        final int serverPort = Integer.parseInt(args[1]);
        final String userName = args[2];
        final String password = args[3];
        final int threadNum = Integer.parseInt(args[4]);
        final String srcFilePath = args[5];
        final String destDirPath = args[6];
        //
        ExecutorService es = Executors.newFixedThreadPool(threadNum);
        for (int i = 0; i < threadNum; i++) {
            es.submit(new Runnable() {

                @Override
                public void run() {
                    boolean success = false;
                    String fileName = UUID.randomUUID().toString();
                    while (!success) {
                        try {
                            FTPClient client = new FTPClient();
                            client.connect(serverHost, serverPort);
                            try {
                                int replyCode = client.getReplyCode();
                                if (!FTPReply.isPositiveCompletion(replyCode)) {
                                    LOGGER.error("Connect to server error");
                                } else {
                                    if (client.login(userName, password)) {
                                        client.setFileType(FTP.BINARY_FILE_TYPE);
                                        client.enterLocalPassiveMode();
                                        //
                                        BufferedInputStream stream = new BufferedInputStream(new FileInputStream(srcFilePath));
                                        try {
                                            final String destFilePath = destDirPath + "/" + fileName;
                                            long start = System.currentTimeMillis();
                                            LOGGER.info(String.format("Starting upload file %s", destFilePath));
                                            client.storeFile(destFilePath, stream);
                                            LOGGER.info(String.format("Finished uploading file %s. Costed %s s", destFilePath, ((System.currentTimeMillis() - start) / 1000.0)));
                                            success = true;
                                        } finally {
                                            stream.close();
                                        }
                                    } else {
                                        LOGGER.error("Login error");
                                    }
                                }
                            } finally {
                                if (client.isConnected()) {
                                    client.disconnect();
                                }
                            }
                        } catch (Exception ex) {
                            LOGGER.error("Ftp error", ex);
                        }
                    }

                }
            });
        }
        es.shutdown();
    }
}
